import { Descriptions, Table, Tooltip, Space, Modal, Button, Tag, Input } from 'antd';
import { PROJECT_QA_CASE_SCENE } from '@/consts/project'
import UserBrief from '@/components/UserBrief'
import TextButton from '@/components/TextButton';
import { QuestionCircleOutlined } from '@ant-design/icons'
import styles from './style.less'
import { useEffect } from 'react';
import { useState } from 'react';
import { completeCasePlanDetail } from '@/services/project/casePlan';
import BugAddModal from '../../ProjectBug/BugAddModal'

const QaCaseDetailModal = (props) => {

    const {
        visible,
        qaCase,
        qaCaseExecute,
        mode = "view",
        onCancel,
        onExecuteComplete
    } = props;

    const [executeResult, setExecuteResult] = useState({});
    const [remarkValue, setRemarkValue] = useState('');
    const [completeLoading, setCompleteLoading] = useState(false);
    const [addBugModalVisiable, setAddBugModalVisiable] = useState(false);
    const [addBugDefaultValue, setAddBugDefaultValue] = useState({});

    useEffect(() => {
        if (qaCaseExecute) {
            // console.log(qaCaseExecute)
            setRemarkValue(qaCaseExecute.remark)
            setExecuteResult(qaCaseExecute.executeResult)
        }
    }, [qaCaseExecute])

    useEffect(() => {
        if (!visible) {
            setRemarkValue('');
            setExecuteResult({})
        }
    }, [visible])


    const onRemarkChange = (e) => {
        setRemarkValue(e.target.value)
    }

    const onCompleteCase = () => {
        setCompleteLoading(true)
        let successCnt = 0, failedCnt = 0;
        let tempExecuteResult = executeResult || {}
        for (let index in qaCase.stepsExpect) {
            let step = qaCase.stepsExpect[index];
            let result = tempExecuteResult[step.id]
            if (result === 0) {
                failedCnt++;
            } else if (result === 1) {
                successCnt++
            } else {
                successCnt++
                tempExecuteResult[step.id] = 1
            }
        }
        let data = {
            remark: remarkValue,
            executeResult: tempExecuteResult,
            successCnt: successCnt,
            failedCnt: failedCnt,
            versions: qaCaseExecute.versions,
            caseName: qaCase.name
        }
        completeCasePlanDetail(qaCase.projectId,
            qaCase.projectQaItemId,
            qaCaseExecute.projectQaCasePlanId,
            qaCaseExecute.id, data).then(({ success }) => {
                setCompleteLoading(false)
                if (success && onExecuteComplete) {

                    onExecuteComplete({
                        id: qaCaseExecute.id,
                        isExecute: 1,
                        ...data,
                        versions: qaCaseExecute.versions + 1,
                    })
                }
            })
    }

    const columns = [{
        title: "步骤",
        dataIndex: 'step',
        key: (index) => index,
        fixed: 'left'
    },
    {
        title: "期望",
        dataIndex: 'expect',
        key: 'expect',
    }]
    if (!qaCase) {
        return <></>;
    }

    const filterColumn = (columns) => {
        if (mode === 'execute') {
            return [...columns,
            {
                title: "是否成功",
                dataIndex: 'executeResult',
                key: 'id',
                width: "72px",
                render: (text, record) => {
                    // console.log(executeResult)
                    if (!executeResult || executeResult[record.id] === undefined) {
                        return <Tag>未执行</Tag>
                    }
                    return executeResult[record.id] === 1 ? <Tag color='#87d068'>是</Tag> : <Tag color='#f50'>否</Tag>;
                }
            }, {
                title: <Tooltip title="默认为成功">操作<QuestionCircleOutlined /></Tooltip>,
                dataIndex: 'action',
                key: 'action',
                width: "100px",
                fixed: 'left',
                render: (text, record) => (
                    <Space>
                        <TextButton onClick={() => {
                            let tmpExecuteResult = executeResult || {};
                            tmpExecuteResult[record.id] = 1;
                            setExecuteResult({ ...tmpExecuteResult })
                        }}>成功</TextButton>
                        <TextButton type="danger" onClick={() => {
                            let tmpExecuteResult = executeResult || {};
                            tmpExecuteResult[record.id] = 0;
                            setExecuteResult({ ...tmpExecuteResult })
                        }}>失败</TextButton>
                        <TextButton type="danger" onClick={() => {
                            let tmpExecuteResult = executeResult || {};
                            tmpExecuteResult[record.id] = 0;
                            setExecuteResult({ ...tmpExecuteResult })
                            setAddBugDefaultValue({
                                name: qaCase.moduleName ? `【${qaCase.moduleName}】${qaCase.name} - ${record.step}` : `${qaCase.name} - ${record.step}`,
                                steps: record.step,
                                expect: record.expect,
                                projectQaItemId: qaCase.projectQaItemId,
                                projectQaCaseId: qaCase.id,
                                projectQaCaseName: qaCase.name
                            })
                            setAddBugModalVisiable(true)
                        }}>失败新增bug</TextButton>
                    </Space>
                )
            }]
        }
        return columns
    }

    const footerRender = mode === 'execute' ? <Button type="primary" loading={completeLoading} onClick={onCompleteCase}>完成</Button> : null
    return <>
        <Modal
            visible={visible}
            destroyOnClose
            width="60%"
            footer={footerRender}
            zIndex="999"
            onCancel={() => {
                if (onCancel) {
                    onCancel()
                }
            }}
        >

            <Descriptions size="small" column={2}>
                <Descriptions.Item span={2}>
                    <h1>{qaCase.name}</h1>
                </Descriptions.Item>
                <Descriptions.Item label="模块" span={1}>
                    {qaCase.moduleName}
                </Descriptions.Item>
                <Descriptions.Item label="类型">
                    {PROJECT_QA_CASE_SCENE[qaCase.scene]?.name}
                </Descriptions.Item>
                <Descriptions.Item label="已执行次数" span={1}>
                    {qaCase.runCnt}
                </Descriptions.Item>
                <Descriptions.Item label="负责人">
                    <UserBrief user={qaCase.user}></UserBrief>
                </Descriptions.Item>
                <Descriptions.Item label="步骤期望" span={2}>
                </Descriptions.Item>
                <Descriptions.Item span={2}>
                    <Table className={styles.stepsExpect}
                        pagination={false}
                        rowKey="step"
                        size="small"
                        columns={filterColumn(columns)}
                        dataSource={qaCase.stepsExpect}
                        locale={{
                            emptyText: "暂无数据"
                        }}
                    />
                </Descriptions.Item>
                {(mode === "execute") && (
                    <>
                        <Descriptions.Item label="备注" span={2}></Descriptions.Item>
                        <Descriptions.Item span={2}>
                            <Input.TextArea
                                value={remarkValue}
                                maxLength={200}
                                showCount
                                onChange={onRemarkChange}
                                style={{ width: "100%" }}>
                            </Input.TextArea>
                        </Descriptions.Item>
                    </>
                )}
            </Descriptions >
        </Modal>
        <BugAddModal
            projectId={qaCase.projectId}
            onCancel={() => {
                setAddBugModalVisiable(false)
            }}
            defaultValue={addBugDefaultValue}
            onSaveSuccess={() => {
                setAddBugModalVisiable(false)
                setAddBugDefaultValue({})
            }}
            visible={addBugModalVisiable} />
    </>
}


export default QaCaseDetailModal;